use crate::logger;
use anyhow::Result;
use std::fs;

use super::add_redux_template::copy_redux_template_to_project;

pub fn update_state_management_by_choose(
    project_dir: &std::path::PathBuf,
    state: &str,
) -> Result<(), std::io::Error> {
    let mut path = std::path::PathBuf::from(project_dir);
    path.push("src/main.tsx");
    let content = fs::read_to_string(&path)?;

    let modified_content = match state {
        "recoil" => {
            logger::update_react_project("reoil的配置");
            insert_recoil_root(&content)
        }
        "redux" => {
            logger::update_react_project("redux的配置");
            copy_redux_template_to_project(project_dir)?;
            insert_redux_root(&content)
        }
        _ => content,
    };

    fs::write(path, modified_content)?;

    Ok(())
}

fn insert_recoil_root(content: &str) -> String {
    let recoil_import = "import { RecoilRoot } from 'recoil';";
    let recoil_wrapper = "<RecoilRoot>\n<App />\n</RecoilRoot>";

    content
        .replace("import './index.css';", &format!("import './index.css';\n{}", recoil_import))
        .replace("<App />", recoil_wrapper)
}

fn insert_redux_root(content: &str) -> String {
    let redux_import = "import { Provider } from 'react-redux';\nimport { store } from './store';";
    let redux_wrapper = "<Provider store={store}>\n<App />\n</Provider>";

    content
        .replace("import './index.css';", &format!("import './index.css';\n{}", redux_import))
        .replace("<App />", redux_wrapper)
}
